package com.hxtec.polaris.service.impl;

import com.hxtec.polaris.entity.ShopUser;
import com.hxtec.polaris.mapper.ShopUserMapper;
import com.hxtec.polaris.model.ShopUserEntity;
import com.hxtec.polaris.repository.UserRepository;
import com.hxtec.polaris.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserRepository userRepository;
    private Calendar calendar = Calendar.getInstance();
    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Resource
    private ShopUserMapper shopUserMapper;

    @Override
    public ShopUserEntity getUser() {
        String mobile = SecurityContextHolder.getContext().getAuthentication().getName();
        Optional<ShopUserEntity> byMobile = userRepository.findByMobile(mobile);
        if (byMobile.isPresent()){
            byMobile.get().setPassword(null);
            return byMobile.get();
        }
        return null;
    }


    @Override
    public void create(String mobile, String password) throws Exception {
        ShopUserEntity user = ShopUserEntity.builder()
                .mobile(mobile)
                .password(encoder.encode(password))
                .state("0")
                .isDelete("N").build();
        if (userRepository.findByMobile(mobile).isPresent()) {
            throw new Exception("user has been exist!");
        }
        userRepository.save(user);
    }

    @Override
    public ShopUser getUserInfoByPhone(String phone) {
        Example example=new Example(ShopUser.class);
        example.createCriteria().andEqualTo("mobile",phone);
        return shopUserMapper.selectOneByExample(example);
    }

    @Override
    @Cacheable(value = "verifyCode")
    public int verify(String number) {
        return (int) ((Math.random() * 9 + 1) * 100000);
    }

    @Override
    public void bind(String openid) {
        ShopUserEntity one = getUser();
        one.setWxId(openid);
        userRepository.save(one);
    }

    @Override
    public String getUserPhonenumber(){
        return SecurityContextHolder.getContext().getAuthentication().getName();
    }

    @Override
    public ShopUser getUserInfo() {
        String mobile = SecurityContextHolder.getContext().getAuthentication().getName();
        return shopUserMapper.getUserInfoByPhone(mobile);
    }
}
